#!/usr/bin/env php
<?php
/**
 * This file is part of Swow
 *
 * @link     https://github.com/swow/swow
 * @contact  twosee <twosee@php.net>
 *
 * For the full copyright and license information,
 * please view the LICENSE file that was distributed with this source code
 */

require_once __DIR__ . '/../tools.php';

use function Swow\Tools\br;
use function Swow\Tools\error;
use function Swow\Tools\notice;
use function Swow\Tools\log;
use function Swow\Tools\ok;
use function Swow\Tools\warn;
use function Swow\Tools\passthru;

if (PHP_OS_FAMILY === 'Windows') {
    error('Not supported on Windows temporarily');
}

$workSpace = realpath(__DIR__ . '/../../ext');
$swowSo = "{$workSpace}/.libs/swow.so";

$options = getopt('', ['rebuild', 'show-log', 'debug', 'enable::']);

$commandArray = ["cd {$workSpace}"];

if (isset($options['rebuild'])) {
    if (file_exists("{$workSpace}/Makefile")) {
        $commandArray[] = './clean.sh';
    }
    $commandArray[] = 'phpize --clean';
}
if (!file_exists("{$workSpace}/configure") || isset($options['rebuild'])) {
    $commandArray[] = 'phpize';
}
if (!file_exists("{$workSpace}/Makefile") || isset($options['rebuild'])) {
    $configureOptions = isset($options['debug']) ? '--enable-swow-debug ' : '';
    $configureOptions = isset($options['enable']) ? $configureOptions . $options['enable'] : $configureOptions;
    $commandArray[] = "./configure {$configureOptions}";
}

// TODO: use Swow\Cpu module
$cpuCount = (int) shell_exec("{$workSpace}/deps/libcat/tools/cpu_count.sh");
if ($cpuCount <= 0) {
    $cpuCount = 4;
}
// TODO: CFLAGS/CXXFLAGS Werror
$commandArray[] = isset($options['show-log']) ? "make -j{$cpuCount}" : "make -j{$cpuCount} > /dev/null";

$command = implode(" && \\\n", $commandArray);

$status = passthru($command);
if ($status !== 0) {
    error('Make failed');
}
ok('Make complete');
br();

$checkCommand = "/usr/bin/env php -n -d extension={$swowSo} --ri swow";
ob_start();
$status = passthru($checkCommand);
$swowInfo = ob_get_clean();
if ($status === 0) {
    log($swowInfo);
} else {
    warn("Get extension info failed");
}

if (getmyuid() !== 0) {
    notice('Install the extension to your system requires root privileges');
    $sudo = 'sudo';
} else {
    $sudo = '';
}
passthru("cd {$workSpace} && {$sudo} make install");

br();
ok('Do\'not forget to add \'extension=swow\' to your PHP ini');
